import datetime

from flask import g
from flask_restful import Resource
from flask_restful.reqparse import RequestParser

from comment.modules import db
from comment.modules.debt_repay import Debtor_repay
from comment.modules.user import User
from financial.resources.transaction.serializer import RepayPlanSerializer


class RepayPlan(Resource):
    """还款的资源类"""

    def get(self):
        """查询某一个（匹配成功的）债券所对应的还款计划"""
        rp = RequestParser()
        rp.add_argument('debt_id')

        args = rp.parse_args()
        debt_id = int(args.get('debt_id'))
        repay_list = Debtor_repay.query.filter(Debtor_repay.claimsId == debt_id).all()
        data = RepayPlanSerializer(repay_list).to_dict()
        return {'msg': 'success', 'data': data}

    def post(self):
        """还款到指定的某个还款计划的某一期"""
        rp = RequestParser()
        rp.add_argument('repay_id')  # 还款计划的ID
        rp.add_argument('repayAmount')  # 当期应该还款的金额
        args = rp.parse_args()
        repay_id = int(args.get('repay_id'))
        repay_money = float(args.get('repayAmount'))

        user_id = g.user_id
        user = User.query.filter(User.id == user_id).first()

        # 判断用户的账户余额是否足够还款
        if user.accountInfo.balance < repay_money:
            return {'message': '可用余额不足', 'code': 20005}
        else:
            user.accountInfo.balance = float(user.accountInfo.balance) - repay_money
            repay = Debtor_repay.query.filter(Debtor_repay.id == repay_id).first()
            # 更改还款状态
            repay.isReturned = 1
            # 记录还款日期
            repay.recordDate = datetime.datetime.now()
            db.session.commit()
            return {'msg': 'success'}
